//
// Created by Max on 2025/5/28.
//
#include "MicConfig.h"
#include "MicThread.h"
#include "AnalysisFile.h"

MicThread *MicThread::s_pMicThread = nullptr;
std::mutex MicThread::s_Mutex;
static MI_U8 readBuff[49152] = {0}; // mtk需要读这个数值
static std::string filePath = "/storage/emulated/0/recorder";

static const char *SAVE_FILE_KEY = "haier.tv.save.mic.file";
static const char *TAG = "MicThread";
static const std::string wavFile = filePath + "/haier.wav";
static const std::string pcmFile = filePath + "/haier.pcm";
static const char *MIC_PROP_KEY = "vendor.haier.mic.num";

MicThread::MicThread() : TvThread(nullptr, nullptr, this), m_pMtkConfig(nullptr) ,
            m_pSaveWav(nullptr),m_bIsMicThreadRunning(false){

}

MicThread::~MicThread() {

}

int MicThread::Init(int channelNum, int sampleRate) {

    if (m_pMtkConfig == nullptr) {
        m_pMtkConfig = new MicConfig();
    }

    if (m_pMtkConfig->Init(channelNum, sampleRate) != MI_SUCCESS) {
        LOGE("m_pMtkMicConfig->Init() failed");
        return MI_FAILURE;
    }

    if (m_pSaveWav == nullptr) {
        m_pSaveWav = new SaveWav(channelNum, sampleRate, PCM_FORMAT_S16_LE);
        m_pSaveWav->openFile(filePath);
        m_pSaveWav->fSeekAfterWavHeader();
        mTotalFramesRead = 0;
    }

    int size = m_pMtkConfig->getMicPeriodSize();
    int count = m_pMtkConfig->getMicPeriodCount();

    LOGD("size === %d, count === %d", size, count);
    TvThread::Run(TvThread::REPEAT);
    m_bIsMicThreadRunning = true;
    return 0;
}

int MicThread::DeInit() {
    TvThread::ExitAndJoin();
    return MI_SUCCESS;
}

bool MicThread::isMicThreadRunning() {
    return m_bIsMicThreadRunning;
}

MicThread *MicThread::getInstance() {
    s_Mutex.lock();
    if (s_pMicThread == nullptr) {
        s_pMicThread = new MicThread();
    }
    s_Mutex.unlock();
    return s_pMicThread;
}

void MicThread::Run(const void *arg) {
    memset(readBuff, 0, sizeof(readBuff));
    int readSize = m_pMtkConfig->readMic(readBuff, sizeof(readBuff));

    if (m_pSaveWav != nullptr) {
        mTotalFramesRead += readSize;
        if (m_pSaveWav->writeToFile(readBuff, 1, readSize) != readSize) {
            LOGE("write error to file ");
        }
    }
}

void MicThread::OnTvMWThreadExit(TvThread *pTvMWThread) {
    if (m_pMtkConfig == nullptr)
    {
        LOGE("m_pMtkMicConfig is nullptr");
        m_bIsMicThreadRunning = false;
        return;
    }

    if (m_pMtkConfig->DeInit() != MI_SUCCESS)
    {
        LOGD(TAG, "m_pMtkMicConfig->DeInit() failed");
        m_bIsMicThreadRunning = false;
        return;
    }
    if (m_pMtkConfig != nullptr)
    {
        delete m_pMtkConfig;
        m_pMtkConfig = nullptr;
    }
    if (m_pSaveWav)
    {
        m_pSaveWav->saveWav2File(mTotalFramesRead);
        m_pSaveWav->closeFile();
        delete m_pSaveWav;
        m_pSaveWav = nullptr;
    }
    m_bIsMicThreadRunning = false;

    LOGE("OnTvMWThreadExit OnTvMWThreadExits OnTvMWThreadExit");
}
